package com.leetcode.test.string;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;

/**
 * https://leetcode-cn.com/explore/learn/card/array-and-string/200/introduction-to-string/779/
 */
public class 二进制求和 {

	@Test
	public void main() {
		Assert.assertEquals("10101", addBinary("1010", "1011"));
		Assert.assertEquals("100", addBinary("11", "1"));
	}

	public static String addBinary(String a, String b) {
		// 进位
		int           up = 0;
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < Math.max(a.length(), b.length()); i++) {
			int ai = 0;
			int bi = 0;

			// 从最低位算起
			if (a.length() - 1 - i >= 0) {
				ai = Integer.valueOf(String.valueOf(a.charAt(a.length() - 1 - i)));
			}
			if (b.length() - 1 - i >= 0) {
				bi = Integer.valueOf(String.valueOf(b.charAt(b.length() - 1 - i)));
			}

			int sum = ai + bi + up;

			if (sum >= 2) {
				up = 1;
				sum = sum - 2;
			} else {
				up = 0;
			}

			sb.insert(0, sum + "");
		}

		if (up == 1) {// 还有进位
			sb.insert(0, "1");
		}

		return sb.toString();
	}
}
